package com.qn.gateway.config;

import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * qingniu-cloud user source analysis
 *
 * @Author: TXG
 * @Date: 2024/6/11
 * @Version V0.0.2
 */
@Configuration
public class SaTokenConfigure {
    /**
     * 注册 Sa-Token全局过滤器
     * @return
     */
    @Bean
    public SaReactorFilter getSaReactorFilter() {
        return new SaReactorFilter()
                // 拦截地址  拦截全部path
                .addInclude("/**")
                //用户注册登录
                .addExclude("/meta/test/login")
                .addExclude("/meta/authentication/login")
                .addExclude("/meta/authentication/register")
                //访客探针放行
                .addExclude("/visitor/JsSdk/**")
                .addExclude("/visitor/event/**")

                //TODO：正式环境需要移除下列接口
                //API文档相关
                .addExclude("/favicon.ico")
                .addExclude("/doc.html")
                .addExclude("/webjars/**")
                .addExclude("/v3/**")
                //swagger API放行
                .addExclude("/meta/v3/api-docs")
                .addExclude("/visitor/v3/api-docs")
                .addExclude("/analyze/v3/api-docs")
                //测试API放行
                .addExclude("/fingerprint")
                .addExclude("/routes")
                //analyze接口测试是
                .addExclude("/analyze/**")

                // 鉴权方法：每次访问进入
                .setAuth(obj -> {
                    // 登录校验 -- 拦截所有路由，并排除/user/doLogin 用于开放登录
                    SaRouter.match("/**", r -> StpUtil.checkLogin());
                })
                .setError(e -> {
                    // 异常处理方法：每次setAuth函数出现异常时进入
                    return new SaResult(401, e.getMessage(), null);
                });
    }

}

